package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.SelectCouponAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.CouponModel;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择优惠券的界面
 * Created by ivany on 2016/1/13.
 */
public class SelectCouponActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private FrameLayout mFrame_noCoupon, mFrame_haveCoupon;
    private ListView mListView;
    private Button mBtn_nouse;
    private SelectCouponAdapter mAdapter;
    private List<CouponModel> mData;
    private String TAG = "SelectCouponActivity";
    private int mStoreId;
    private Double mAccount;
    private int mLastCouponId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_coupon);
        Tools.changeSystemBar(this);
        setTitle("选择优惠券");
        initViews();
    }

    @Override
    public void findViewByIds() {
        mFrame_noCoupon = (FrameLayout) findViewById(R.id.select_coupon_noCoupon);
        mFrame_haveCoupon = (FrameLayout) findViewById(R.id.select_coupon);
        mListView = (ListView) findViewById(R.id.select_coupon_list);
        mBtn_nouse = (Button) findViewById(R.id.select_coupon_nouse);
    }

    @Override
    public void initListener() {
        mData = new ArrayList<>();
        mAdapter = new SelectCouponAdapter(this);
        mListView.setOnItemClickListener(this);
        mBtn_nouse.setOnClickListener(this);
    }

    @Override
    public void initData() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查网络");
        }

        String tmId = SPHelper.getTmId();
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", tmId);

        Intent intent = getIntent();
        mStoreId = intent.getIntExtra("storeId", 0);
        mAccount = intent.getDoubleExtra("account", 0.0d);
        //找出当前店铺的上次勾选的优惠券
        for (int i = 0; i < ConfirmOrderActivity.LAST_CHOOSE_COUPON.size(); i++) {
            if (ConfirmOrderActivity.LAST_CHOOSE_COUPON.get(i).containsKey(mStoreId)) {
                mLastCouponId = ConfirmOrderActivity.LAST_CHOOSE_COUPON.get(i).get(mStoreId);
            }
        }

        if (intent.hasExtra("storeId")) {//当是从确认订单界面跳转过来的时候
            params.addBodyParameter("tsId", mStoreId + "");
            params.addBodyParameter("status", "2");
        } else {
            params.addBodyParameter("status", "1");
        }
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.TICKET_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取优惠券列表失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObject.getJSONArray("list");
                            if (list.length() > 0) {
                                mData.clear();
                                mFrame_noCoupon.setVisibility(View.GONE);
                                mFrame_haveCoupon.setVisibility(View.VISIBLE);
                                mBtn_nouse.setVisibility(View.VISIBLE);
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject temp = list.getJSONObject(i);
                                    String tsName = temp.getString("tsName");
                                    int ttId = temp.getInt("ttId");
                                    String ttNumber = temp.getString("ttNumber");
                                    String ttMoney = temp.getString("ttMoney");
                                    String ttStart = temp.getString("ttStart");
                                    String ttEnd = temp.getString("ttEnd");
                                    String ttTop = temp.getString("ttTop");

                                    CouponModel model1 = new CouponModel();

                                    model1.setId(ttId);
                                    model1.setName(tsName);
                                    model1.setCondition(ttTop);
                                    model1.setNumber(ttNumber);
                                    model1.setValue(new DecimalFormat("0.00").format(Double.valueOf(ttMoney)));
                                    model1.setStartDate(TimeUtils.convertTimeYMD(Long.valueOf(ttStart)));
                                    model1.setEndDate(TimeUtils.convertTimeYMD(Long.valueOf(ttEnd)));
                                    if (mLastCouponId != -1 && mLastCouponId == ttId) {
                                        model1.setIsSelect(true);
                                    } else {
                                        model1.setIsSelect(false);
                                    }
                                    mData.add(model1);
                                }
//                                TODO 需换成真是操作字段名成
//                                mAdapter.setData(mData);
                                mListView.setAdapter(mAdapter);
                                mAdapter.notifyDataSetChanged();
                            } else {
                                mFrame_noCoupon.setVisibility(View.VISIBLE);
                                mFrame_haveCoupon.setVisibility(View.GONE);
                                mBtn_nouse.setVisibility(View.GONE);
                            }
                        } else {
                            mBtn_nouse.setVisibility(View.GONE);
                            mFrame_noCoupon.setVisibility(View.VISIBLE);
                            mFrame_haveCoupon.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showMsg("当前网络不可用,请解除您的网络设置");
            }
        });


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Double condition = Double.valueOf(mData.get(position).getCondition());
        if (condition<=mAccount) {
            for (int i = 0; i < mData.size(); i++) {
                if (mData.get(i).isSelect()) {
                    if (i == position) {//双击返回
                        //记录选择的优惠券
                        Map<Integer, Integer> map = new HashMap<>();
                        map.put(mStoreId, mData.get(i).getId());
                        ConfirmOrderActivity.LAST_CHOOSE_COUPON.add(map);
                        Intent intent = new Intent();
                        intent.putExtra("couponId", mData.get(position).getId());
                        intent.putExtra("value", mData.get(position).getValue());
                        setResult(Constant.SELECT_COUPON_RESULT, intent);
                        finish();
                    }
                    mData.get(i).setIsSelect(false);
                }
            }
            mData.get(position).setIsSelect(true);
            mAdapter.notifyDataSetChanged();
        }else{
            showMsg("不符合使用该优惠券的条件");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_coupon_nouse:
                for (int i = 0; i < mData.size(); i++) {
                    mData.get(i).setIsSelect(false);
                    mAdapter.notifyDataSetChanged();
                }

                //当不使用优惠券的时候，从记录列表中出除去
                for (int i = 0; i < ConfirmOrderActivity.LAST_CHOOSE_COUPON.size(); i++) {
                    if (ConfirmOrderActivity.LAST_CHOOSE_COUPON.get(i).containsKey(mStoreId)) {
                        ConfirmOrderActivity.LAST_CHOOSE_COUPON.remove(i);
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("couponId", 0);
                intent.putExtra("value", "0");
                setResult(Constant.SELECT_COUPON_RESULT, intent);
                finish();
                break;
        }
    }
}
